<template>
  <div id="picture-search-page">
    <h1>以图搜图</h1>
    <h2>原图</h2>
    <a-image
      :alt="picture.name"
      :src="picture.url ?? picture.thumbnailUrl"
      :width="300"
      :height="300"
      style="object-fit: cover"
    />
    <h2>搜图结果</h2>

    <a-tabs v-model:activeKey="activeKey" type="card" @change="getPictureList">
      <a-tab-pane key="360" tab="360搜图">
        <!--    图片列表-->
        <a-list
          :loading="loading"
          item-layout="vertical"
          :grid="{ gutter: 16, xs: 1, sm: 1, md: 2, lg: 2, xl: 3, xxl: 4 }"
          :data-source="pictureList"
        >
          <template #renderItem="{ item }">
            <a-list-item>
              <a-skeleton :loading="loading" active avatar>
                <a-card hoverable style="width: 300px">
                  <template #cover>
                    <a-image
                      :alt="item.title"
                      :src="item.imgUrl"
                      :preview="false"
                      :placeholder="true"
                      style="object-fit: cover; height: 400px"
                    />
                  </template>

                  <template #actions>
                    <a-space @click="(e) => doAddPicture(e, item.imgUrl)">
                      <PlusOutlined />
                      加入我的空间
                    </a-space>
                  </template>
                </a-card>
              </a-skeleton>
            </a-list-item>
          </template>
        </a-list>
        <!--    分页-->
        <a-pagination
          v-model:current="searchParams.current"
          :total="total"
          @change="onPageChange"
        />
      </a-tab-pane>
      <a-tab-pane key="pexels" tab="Pexels搜图" force-render>
        <!--    图片列表-->
        <a-list
          :loading="loading"
          item-layout="vertical"
          :grid="{ gutter: 16, xs: 1, sm: 1, md: 2, lg: 2, xl: 3, xxl: 4 }"
          :data-source="picturePexelList"
        >
          <template #renderItem="{ item }">
            <a-list-item>
              <a-skeleton :loading="loading" active avatar>
                <a-card hoverable style="width: 300px">
                  <template #cover>
                    <img alt="暂无" :lazy="true" :src="item.thumbUrl" style="object-fit: cover; height: 400px" />
                  </template>

                  <template #actions>
                    <a-space @click="(e) => doAddPicture(e, item.thumbUrl)">
                      <PlusOutlined />
                      加入我的空间
                    </a-space>
                  </template>
                </a-card>
              </a-skeleton>
            </a-list-item>
          </template>
        </a-list>
        <a-pagination
          v-model:current="searchParams.current"
          :total="total"
          @change="onPageChange"
        />
      </a-tab-pane>
    </a-tabs>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import {
  getPictureVoByIdUsingGet,
  searchImageByPexelsUsingPost,
  searchImageUsingPost,
  uploadPictureByUrlUsingPost,
} from '@/api/pictureController.ts'
import { useRoute, useRouter } from 'vue-router'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { listSpaceVoByPageUsingPost } from '@/api/spaceController.ts'
import { useUserStore } from '@/stores/user.ts'

// 控制tab
const activeKey = ref('360')
const picture = ref<API.PictureVO>({})
// 查询图片
const route = useRoute()
const getPicture = async () => {
  const res = await getPictureVoByIdUsingGet({
    id: route.query.id,
  })
  if (res.data.code != 0) {
    return
  }
  picture.value = res.data.data
}
const router = useRouter()
//  total

// 获取spaceId
const space = ref<API.SpaceVO>({})
const userStore = useUserStore()
const checkAuth = async () => {
  //   判断是否登录
  if (!userStore.isLogin) {
    message.error('请先登录')
    router.replace('/user/login')
    return
  }
  // 获取用户空间
  const res1 = await listSpaceVoByPageUsingPost({
    current: 1,
    pageSize: 1,
    userId: userStore.userInfo.id,
  })

  if (res1.data.code != 0) {
    message.error('请先创建空间')
    return
  }
  // 获取space
  space.value = res1.data.data?.records[0]
}

// 加入我的空间
const doAddPicture = async (e, url: string) => {
  e.stopPropagation()
  await checkAuth()
  await handleUpload(url)
  await router.push({
    path: '/space/my',
  })
}

// 上传图片url
const handleUpload = async (url: string) => {
  loading.value = true
  const res = await uploadPictureByUrlUsingPost({
    spaceId: space.value.id,
    fileUrl: url,
  })
  if (res.data.code != 0) {
    return
  }
  loading.value = false
}
// 获取数据
const pictureList = ref<API.SoImageSearchResult[]>([])
const picturePexelList = ref<API.ImageSearchResult[]>([])
const loading = ref(false)
// 参数
const searchParams = ref<API.SearchPictureByPictureRequest>({
  current: 1,
  pageSize: 10,
  id: route.query.id,
})

// 获取搜图结果
const total = ref(0)
const getPictureList = async () => {
  loading.value = true
  // 判断tab栏
  let res
  if (activeKey.value == '360') {
    res = await searchImageUsingPost({
      ...searchParams.value,
    })
    pictureList.value = res.data?.data?.records
    total.value = res.data?.data?.total
  } else {
    res = await searchImageByPexelsUsingPost({
      ...searchParams.value,
    })
    picturePexelList.value = res.data?.data
  }
  if (res.data.code != 0) {
    return
  }

  loading.value = false
}

// 分页
const onPageChange = (page: number, pageSize: number) => {
  searchParams.value.current = page
  searchParams.value.pageSize = pageSize
  getPictureList()
}

onMounted(() => {
  getPictureList()
  getPicture()
})
</script>

<style scoped lang="scss">
#picture-search-page {
  .search {
    width: 60%;
    margin: 0 auto;
  }

  .tagList {
    margin-bottom: 16px;
  }
}
</style>
